<template>
  <el-dialog :title="title" :visible.sync="visible" :width="width" append-to-body @close="cancel">
    <el-row :gutter="48">
      <el-col :span="5" :xs="24">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="部门名称" size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
        </div>
        <div class="head-container">
          <el-tree ref="tree" :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" default-expand-all @node-click="handleNodeClick" />
        </div>
      </el-col>
      <el-col :span="19" :xs="24">
        <!-- 查询、筛选条件 -->
        <el-form v-show="showSearch" ref="queryForm" :model="queryParams" label-position="left" label-width="85px">
          <el-row :gutter="36">
            <el-col :xs="24" :sm="9">
              <el-form-item label="登录账号：" prop="userName">
                <el-input v-model="queryParams.userName" placeholder="请输入" size="small" @keyup.enter.native="loadData" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="9">
              <el-form-item label="手机号码：" prop="phonenumber">
                <el-input v-model="queryParams.phonenumber" placeholder="请输入" size="small" @keyup.enter.native="loadData" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="6">
              <span class="search-advancedButton">
                <el-button type="primary" size="small" @click="loadData">查 询</el-button>
                <el-button size="small" @click="resetQuery">重 置</el-button>
              </span>
            </el-col>
          </el-row>
        </el-form>

        <!-- 表格 -->
        <el-table ref="table" v-loading="loading" :row-key="(row) => row.userId" :data="dataSource" @selection-change="handleSelectionChange">
          <template slot="empty">
            <el-empty />
          </template>
          <!-- 超级管理员不可选 -->
          <el-table-column v-if="multi" type="selection" :reserve-selection="true" :selectable="(row) => !row.admin" width="80" fixed="left" align="center" />
          <el-table-column v-else width="80" fixed="left" align="center">
            <template slot-scope="{row}">
              <el-radio v-model="selectRadio" :disabled="row.admin" :label="row.userId" @change="handleRadioChange(row)">{{ "" }}</el-radio>
            </template>
          </el-table-column>
          <el-table-column key="nickName" label="用户名" align="left" prop="nickName" :show-overflow-tooltip="true">
            <template slot-scope="{row}">
              <div class="table_nickName">
                <div style="margin:2px 8px 0 0">
                  <el-avatar v-if="row.avatar" :key="row.avatar" shape="circle" size="medium" :src="`${process}${row.avatar}`" />
                  <el-avatar v-else>
                    <img src="@/assets/images/profile.png">
                  </el-avatar>
                </div>
                {{ row.nickName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column key="userName" label="登录账号" align="center" prop="userName" :show-overflow-tooltip="true" />
          <el-table-column key="phonenumber" label="手机号码" align="center" prop="phonenumber" />
          <el-table-column key="deptName" label="所属部门" align="center" prop="dept.deptName" />
        </el-table>
        <!-- 分页 -->
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="loadData" />
      </el-col>
    </el-row>
    <!-- 确认 取消 按钮 -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
/**
 * auther: cuihaodong
 * desc: 选择用户
 */
import { listUser } from '@/api/system/user'
import { treeselect } from '@/api/system/dept'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'SelectUserByDeptModal',
  props: {
    value: {
      type: String,
      default: ''
    },
    // 是否多选 | Boolean
    multi: {
      type: Boolean,
      default: false
    },
    show: {
      type: Boolean,
      default: false
    },
    width: {
      type: [String, Number],
      default: '70%'
    }
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      visible: false,
      // 显示搜索条件
      showSearch: true,
      // 选中数组
      selectRadio: undefined,
      dataSource: [],
      selectionRows: [],
      selectUserRows: [],
      selectUserIds: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined
      },
      // 总条数
      total: 0,
      title: '请选择指派人',
      // 部门树
      deptName: undefined,
      deptOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  // 判断是开发or生产环境
  computed: {
    process() {
      return process.env.VUE_APP_BASE_API
    }
  },
  watch: {
    value: {
      immediate: true,
      handler() {
        this.initUserNames()
      }
    },
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    initUserNames() {
      if (this.value) {
        const userIds = this.value
        listUser({
          userIds,
          pageNum: 1,
          pageSize: 10
        }).then((res) => {
          this.selectionRows = []
          const nickNames = []
          res.rows.forEach((item) => {
            nickNames.push(item.nickName)
            this.selectionRows.push(item)
            if (this.multi) {
              this.$nextTick(() => {
                this.$refs.table.toggleRowSelection(item, true)
              })
            } else {
              this.selectRadio = item.userId
            }
          })
          this.$emit('initComp', nickNames.join(','))
        })
      } else {
        this.$emit('initComp', '')
        this.reset()
      }
    },
    // 查询用户列表
    loadData() {
      this.loading = true
      listUser(this.queryParams)
        .then((res) => {
          this.dataSource = res.rows
          this.total = res.total
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 单选
    handleRadioChange(row) {
      this.selectionRows = []
      this.selectionRows.push(row)
    },
    // 多选
    handleSelectionChange(selection) {
      this.selectionRows = selection
    },
    // 确定
    handleSubmit() {
      this.selectUserRows = this.selectionRows
      this.selectUserIds = this.selectUserRows
        .map((item) => item.userId)
        .join(',')
      this.$emit('ok', this.selectUserRows, this.selectUserIds)
      this.visible = false
      this.reset()
    },
    // 取消
    cancel() {
      this.$emit('update:show', false)
      this.visible = false
      this.reset()
    },
    // 显示弹框
    showModal() {
      this.visible = true
      this.getTreeselect()
      this.initUserNames()
      this.loadData()
    },
    // 查询部门下拉树结构
    getTreeselect() {
      treeselect().then((res) => {
        this.deptOptions = res.data
      })
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.loadData()
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 重置
    reset() {
      if (this.$refs.table) {
        this.$nextTick(() => {
          this.$refs.table.clearSelection()
        })
      }
      this.selectRadio = undefined
      this.selectUserRows = []
      this.selectUserIds = []
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined
      }
      this.loadData()
    },
    // 重置查询
    resetQuery() {
      this.resetForm('queryForm')
      this.loadData()
    }
  }
}
</script>

<style lang="scss" scoped>
.table_nickName {
  margin: 1px 0 !important;
  display: flex;
  align-items: center;
}

::v-deep .el-table__expanded-cell {
  padding: 15px 115px !important;
}
</style>
